<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/inc/core/env.inc.php';

$return["success"] = false;
$return["html"] = null;
$return["jscript"] = null;
$return["error"] = null;

if ($_USER->asPermission('mod_page')) {
	
	//fields controll
	$frmFields = new Fields();
	$frmFields->addFiels("name", "string", $_POST["name"]);
	$frmFields->addFiels("label", "slug", $_POST["label"]);
	$frmFields->addFiels("title", "string", $_POST["title"]);
	$validFields = $frmFields->isValid();
	
	if ($validFields){
		$i = 2;
		$newLabel = $_POST["label"];
		$siteComponent = new Site();
		while (!$siteComponent->searchLabelPage($newLabel)) {
			$newLabel = $_POST["label"].'-'.$i;
			$i++;
		}
		
		$sql = "INSERT INTO ".$_DB->getPrefix()."pages (parent, label, name, date_in)
				VALUES ('".$_POST["parent"]."', '".$newLabel."', '".$_POST["name"]."', now())";
		
		$_DB->query($sql);
		
		$page = new Page($newLabel);
		$return["jscript"] = '$(location).attr("href", "http://'.$_SITE["domain"]."/".$page->get('path').$newLabel.'.html");';
				
		$sql = "INSERT INTO ".$_DB->getPrefix()."page_metatag (id_page, id_meta, text)
				VALUES ('".$page->pId."', '1', '".$_POST["title"]."')";
		
		$_DB->query($sql);
		$return["success"] = true;
		
	} else {
		$return["error"] = 'Error fields not valid.';
	}
	
} else {
	$return["error"] = 'Error not have permission.';
}

echo '('.json_encode($return).')';

?>